package com.car.web.controller.base;

import java.io.IOException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.car.bean.GridObj;
import com.car.bean.MsgObj;
import com.car.bean.PageObj;
import com.car.exception.BaseException;
import com.car.util.CommonUtil;
import com.car.util.Page;
import com.car.util.Result;
import com.car.util.ResultSupport;

/**
 * base Copyright Copyright 2011-7-8 Company aliyun
 *
 * @author huajun.luohj
 * @version 1.0
 *          <p/>
 *          Modification History: Date Author Version Description
 *          ------------------------------------------------------------------
 *          2011-7-8 huajun.luohj 1.0 Initialize Version.
 */

@Controller
public class BaseController {

    private static final Logger logger = Logger.getLogger(BaseController.class);

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(true);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(
                dateFormat, true));
    }

    public Result prapare(BaseVo vo) {
        Result result = new ResultSupport();
        return result;
    }

    protected ModelAndView ajax_success() {
        return ajax_success("操作成功");
    }

    protected ModelAndView ajax_success(String msg) {
        return ajax_success(msg, null);
    }

    protected ModelAndView ajax_success(Object obj) {
        return ajax_success("操作成功", obj);
    }

    protected ModelAndView ajax_success(GridObj obj) {
        return ajax(obj);
    }

    protected ModelAndView ajax_success(String msg, Object obj) {
        return ajax(new MsgObj(msg, obj, true));
    }

    protected ModelAndView ajax_fail() {
        return ajax_fail("操作失败");
    }

    protected ModelAndView ajax_fail(String msg) {
        return ajax_fail(msg, null);
    }

    protected ModelAndView ajax_fail(Object obj) {
        return ajax_fail("操作失败", obj);
    }

    protected ModelAndView ajax_fail(String msg, Object obj) {
        return ajax(new MsgObj(msg, obj, false));
    }

    protected ModelAndView ajax(Object obj) {
        ModelMap modelMap = new ModelMap();
        modelMap.addAttribute("root", obj);
        return new ModelAndView("commonAjaxView", modelMap);
    }

    protected Page getViewPage(PageObj page, Long totalProperty) {
        Page viewPage = new Page();
        int start = page.getStartInt();
        int limit = page.getLimitInt();
        if (limit <= 0) {
            limit = 10;
        }
        int currentPage = start / limit + 1;
        viewPage.setCurrpage(currentPage);
        viewPage.setPagesize(limit);
        viewPage.setTotal(totalProperty);
        return viewPage;
    }

    protected MsgObj getException(Exception e) {
        String msg = "系统出错";
        if (e instanceof BaseException) {
            BaseException nwe_e = (BaseException) e;
            msg = e.getMessage();
            logger.debug(nwe_e.getLayer());
        } else {
            logger.debug("其他错误");
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return new MsgObj(msg, false);
    }

    private Cookie getCookie(String key, String msg) {
        Cookie c = new Cookie(key, URLEncoder.encode(msg));
        c.setMaxAge(5 * 60);
        c.setPath("/");
        return c;
    }

    private HttpServletRequest getRequest() {
        ServletRequestAttributes servletContainer = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        return servletContainer.getRequest();
    }

    protected void error(HttpServletResponse response, String msg,
                         String nextUrl) {
        response.addCookie(this.getCookie("msg", msg));
        response.addCookie(this.getCookie("isSuccess", "false"));
        response.addCookie(this.getCookie("nextUrl", nextUrl));
        try {
            response.sendRedirect(getRequest().getContextPath()
                    + "/sys/info.htm");
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    protected void error(HttpServletResponse response, Exception e) {
        MsgObj msgObj = this.getException(e);
        if (msgObj != null) {
            response.addCookie(this.getCookie("msg", msgObj.getMsg()));
        }
        response.addCookie(this.getCookie("isSuccess", "false"));
        try {
            response.sendRedirect(getRequest().getContextPath()
                    + "/sys/info.htm");
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    protected void success(HttpServletResponse response, String msg,
                           String nextUrl) {
        if (!CommonUtil.isEmpty(msg)) {
            response.addCookie(this.getCookie("msg", msg));
        }
        response.addCookie(this.getCookie("isSuccess", "true"));
        response.addCookie(this.getCookie("nextUrl", nextUrl));
        try {
            response.sendRedirect(getRequest().getContextPath()
                    + "/sys/info.htm");
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}
